import { userModel } from "../models/user";
import { fakeUserModel } from "../models/fakeuser";
import { searchLogModel } from "../models/searchlog";
import { dailyModel } from "../models/dailyrecord";
import { focusModel } from "../models/focusList";
import { dianzanModel } from "../models/dianzan";
import { plModel } from "../models/pl";
import { newsInfo } from "../models/news";
import { shoucangModel } from "../models/shoucang";
import { historyModel } from "../models/history";
import { Context } from "koa";
import { validate } from "../utils/validate";
import { Rules } from "async-validator";
import { sign, verify } from "../utils/auth";
import { resp } from "../utils/res";
import { comparecrypt } from "../utils/bcryptjs";
import { findByProps } from "../utils/crud";

import mongoose from "mongoose";
import { send } from "../utils/email";
import { pageFilter, newpageFilter } from "../utils/pageFilter";
import { fromTime, dealTime } from "../utils/moment";
class userInfo {
  async getCode(ctx: Context) {
    const rules: Rules = {
      email: [
        {
          type: "string",
          required: true,
          message: "邮箱不能为空",
        },
      ],
      type: [
        {
          type: "string",
          required: true,
          message: "验证码类型不能为空",
        },
      ],
    };
    type CODE = {
      email: string;
      type: string;
    };
    const { data, error } = await validate<CODE>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }

    try {
      let code = Math.random().toString(36).substring(7);
      //判断是否在三分钟内
      let findFakeInfoRes = await fakeUserModel.findOne({ email: data.email });
      if (findFakeInfoRes) {
        let nowTime = (new Date().getTime() / 1000).toFixed(0);
        let djs: number = 20;
        var s = Number(nowTime) - Number(findFakeInfoRes.updateTime);
        if (s > djs) {
          let sendRes = await send(data.email, data.type, code);
          if (sendRes) {
            resp.success(ctx, [], `${data.type}发送成功,请打开QQ邮箱查看`);
            // //创建验证码记录
            fakeUserModel
              .findOneAndUpdate(
                { email: data.email },
                {
                  $set: {
                    code: code,
                    updateTime: (new Date().getTime() / 1000).toFixed(0),
                  },
                },
                { new: true }
              )
              .then((res) => {
                console.log(`更新${data.type}成功${res?.code}`);
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          console.log(`请${djs - s}秒后再发送`);
          resp.error(ctx, `请求繁忙`);
        }
      } else {
        let code = Math.random().toString(36).substring(7);
        // //创建验证码记录
        fakeUserModel
          .create({ email: data.email, code: code })
          .then((res) => {
            if (res) {
              console.log(`已发送${data.type}`);
              send(data.email, data.type, code);
            }
          })
          .catch((err) => {
            console.log(err, "新建失败");
          });
      }
    } catch (error) {
      resp.error(ctx, "发送失败,请联系514头条开发人员");
    }
  }
  async register(ctx: Context) {
    const rules: Rules = {
      nickname: [
        {
          type: "string",
          required: true,
          message: "用户名不能为空",
        },
      ],
      email: [
        {
          type: "string",
          required: true,
          message: "邮箱不能为空",
        },
      ],
      password: [
        {
          type: "string",
          required: true,
          message: "密码不能为空",
        },
      ],
      // code: [
      //   {
      //     type: "string",
      //     required: true,
      //     message: "验证码不能为空",
      //   },
      // ],
    };

    type LOGIN = {
      nickname: string;
      email: string;
      password: string;
      // code: string;
    };
    const { data, error } = await validate<LOGIN>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    // let fakeUserInfo = await fakeUserModel.findOne({ email: data.email });
    // if (fakeUserInfo?.code != data.code) {
    //   return resp.error(ctx, "验证码错误或已过期");
    // } else {
    // //创建验证码记录
    // fakeUserModel
    //   .findOneAndUpdate(
    //     { email: data.email },
    //     {
    //       $set: {
    //         code: Math.random().toString(36).substring(7),
    //         updateTime: (new Date().getTime() / 1000).toFixed(0),
    //       },
    //     },
    //     { new: true }
    //   )
    //   .then((res) => {
    //     console.log(`作废验证码成功${res?.code}`);
    //   })
    //   .catch((err) => {
    //     console.log(err);
    //   });
    //然后查找邮箱 如果有此邮箱 就对比密码
    try {
      let findByPropsRes = await findByProps(userModel, {
        email: data.email,
      });
      // if (comparecrypt(data.password, findByPropsRes.password)) { 对比密码是否一直
      if (findByPropsRes) {
        return resp.error(ctx, "该邮箱已注册!");
      } else {
        try {
          let res = await userModel.create({
            nickname: data.nickname,
            email: data.email,
            password: data.password,
          });
          if (res) {
            resp.success(ctx, res, "注册成功！");
          }
        } catch (error: any) {
          return resp.error(ctx, error);
        }
      }
    } catch (error: any) {
      return resp.error(ctx, error);
    }
    // }
  }
  async login(ctx: Context) {
    const rules: Rules = {
      email: [
        {
          type: "string",
          required: true,
          message: "邮箱不能为空",
        },
      ],
      password: [
        {
          type: "string",
          required: true,
          message: "密码不能为空",
        },
      ],
      // code: [
      //   {
      //     type: "string",
      //     required: true,
      //     message: "验证码不能为空",
      //   },
      // ],
    };
    type LOGIN = {
      email: string;
      password: string;
      // code:string
    };
    try {
      const { data, error } = await validate<LOGIN>(ctx, rules);
      if (error) {
        return resp.error(ctx, error);
      }
      // let fakeUserInfo = await fakeUserModel.findOne({ email: data.email });
      // if (fakeUserInfo?.code != data.code) {
      //   return resp.error(ctx, "验证码错误或已过期");
      // } else {
      // //创建验证码记录
      // fakeUserModel
      //   .findOneAndUpdate(
      //     { email: data.email },
      //     {
      //       $set: {
      //         code: Math.random().toString(36).substring(7),
      //         updateTime: (new Date().getTime() / 1000).toFixed(0),
      //       },
      //     },
      //     { new: true }
      //   )
      //   .then((res) => {
      //     console.log(`作废验证码成功${res?.code}`);
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   });
      try {
        let findByPropsRes = await findByProps(userModel, {
          email: data.email,
        });

        if (!findByPropsRes) {
          return resp.error(ctx, "该邮箱未注册");
        } else {
          if (comparecrypt(data.password, findByPropsRes.password)) {
            let signRes = sign({
              email: data.email,
              id: findByPropsRes._id,
            });
            resp.success(
              ctx,
              {
                token: signRes,
              },
              "登陆成功"
            );
          } else {
            return resp.error(ctx, "密码错误");
          }
        }
      } catch (error: any) {
        return resp.error(ctx, error);
      }
      // }
    } catch (error: any) {
      return resp.error(ctx, error);
    }
  }
  async delsearchLog(ctx: Context) {
    let id = ctx.request.body?.id;
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code == 200) {
      if (id) {
        let sRes = await searchLogModel.findOneAndDelete({
          _id: id,
        });
        if (sRes) {
          resp.success(ctx, sRes);
        } else {
          resp.error(ctx);
        }
      } else {
        searchLogModel
          .deleteMany({
            userid: vres.data.id,
          })
          .then((res) => {
            resp.success(ctx, res);
          });
      }
    }
  }
  async addsearchLog(ctx: Context) {
    const rules: Rules = {
      title: [
        {
          type: "string",
          required: true,
          message: "搜索内容不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code == 200) {
      type LOGIN = {
        title: string;
      };
      const { data, error } = await validate<LOGIN>(ctx, rules);
      if (error) {
        return resp.error(ctx, error);
      }
      let sRes = await searchLogModel.create({
        userid: vres.data.id,
        title: data.title,
      });
      if (sRes) {
        resp.success(ctx, sRes);
      } else {
        resp.error(ctx);
      }
    }
  }
  async getsearchLog(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code == 200) {
      let sRes = await searchLogModel.find({ userid: vres.data.id });
      if (sRes) {
        resp.success(ctx, sRes);
      } else {
        resp.error(ctx);
      }
    }
  }
  async getuserinfo(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres = verify(token);
    if (vres.code == 200) {
      let findRes = await userModel.findOne({
        email: (vres.data as any).email,
      });
      if (findRes) {
        resp.success(ctx, findRes);
      }
    } else {
      return resp.error(ctx, "token非法或过期");
    }
  }
  async modifynavator(ctx: Context) {
    const rules: Rules = {
      avator: [
        {
          type: "string",
          required: true,
          message: "头像地址不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres = verify(token);
    if (vres.code == 200) {
      type LOGIN = {
        avator: string;
      };
      const { data, error } = await validate<LOGIN>(ctx, rules);
      if (error) {
        return resp.error(ctx, error);
      }

      let findRes = await userModel.findOneAndUpdate(
        {
          email: (vres.data as any).email,
        },
        {
          $set: {
            avator: data.avator,
          },
        },
        {
          new: true,
        }
      );
      if (findRes) {
        resp.success(ctx, [], "修改成功");
      }
    } else {
      return resp.error(ctx, "token非法或过期");
    }
  }
  async yjtg(ctx: Context) {
    let res = await dailyModel.updateMany(
      { __v: 0 },
      {
        status: true,
      }
    );
    if (res) {
      resp.success(ctx, [], "全部审核通过");
    } else {
      resp.error(ctx);
    }
  }
  async passfbuinfo(ctx: Context) {
    const rules: Rules = {
      id: [
        {
          type: "string",
          required: true,
        },
      ],
      flag: [
        {
          type: "boolean",
          required: true,
        },
      ],
    };
    type LOGIN = {
      id: string;
      flag: boolean;
    };
    const { data, error } = await validate<LOGIN>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let res = await dailyModel.findByIdAndUpdate(data.id, {
      status: data.flag,
    });
    if (res) {
      if (data.flag == true) {
        resp.success(ctx, [], "审核通过");
      } else {
        resp.success(ctx, [], "审核不通过");
      }
    } else {
      resp.error(ctx);
    }
  }
  async modifypassword(ctx: Context) {
    const rules: Rules = {
      code: [
        {
          type: "string",
          required: true,
          message: "验证码不能为空",
        },
      ],
      password: [
        {
          type: "string",
          required: true,
          message: "密码不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres = verify(token);

    if (vres.code == 200) {
      type LOGIN = {
        code: string;
        password: string;
      };
      const { data, error } = await validate<LOGIN>(ctx, rules);
      if (error) {
        return resp.error(ctx, error);
      }
      let fakeUserInfo = await fakeUserModel.findOne({
        email: (vres.data as any).email,
      });
      if (fakeUserInfo?.code != data.code) {
        return resp.error(ctx, "验证码错误或已过期");
      }
      fakeUserModel
        .findOneAndUpdate(
          { email: (vres.data as any).email },
          {
            $set: {
              code: Math.random().toString(36).substring(7),
              updateTime: (new Date().getTime() / 1000).toFixed(0),
            },
          },
          { new: true }
        )
        .then((res) => {
          console.log(`作废验证码成功${res?.code}`);
        })
        .catch((err) => {
          console.log(err);
        });
      let findRes = await userModel.findOneAndUpdate(
        {
          email: (vres.data as any).email,
        },
        {
          $set: {
            password: data.password,
          },
        },
        {
          new: true,
        }
      );
      if (findRes) {
        resp.success(ctx, [], "修改成功");
      }
    } else {
      return resp.error(ctx, "token非法或过期");
    }
  }
  async modifynickname(ctx: Context) {
    const rules: Rules = {
      nickname: [
        {
          type: "string",
          required: true,
          message: "昵称不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres = verify(token);
    if (vres.code == 200) {
      type LOGIN = {
        nickname: string;
      };
      const { data, error } = await validate<LOGIN>(ctx, rules);
      if (error) {
        return resp.error(ctx, error);
      }

      let findRes = await userModel.findOneAndUpdate(
        {
          email: (vres.data as any).email,
        },
        {
          $set: {
            nickname: data.nickname,
          },
        },
        {
          new: true,
        }
      );
      if (findRes) {
        resp.success(ctx, [], "修改成功");
      }
    } else {
      return resp.error(ctx, "token非法或过期");
    }
  }
  async goindex(ctx: Context) {
    await ctx.render("index");
  }
  async gogw(ctx: Context) {
    await ctx.render("gw");
  }
  async gochatgpt(ctx: Context) {
    // resp.error(ctx,'服务器维护')
    await ctx.render("chatgpt");
  }
  async forbidden(ctx: Context) {
    // resp.error(ctx,'服务器维护')
    await ctx.render("forbidden");
  }
  async gobh(ctx: Context) {
    await ctx.render("bh");
  }
  async gohn(ctx: Context) {
    await ctx.render("test");
  }
  async gohnn(ctx: Context) {
    await ctx.render("test1");
  }
  async gohnnn(ctx: Context) {
    await ctx.render("test2");
  }
  async gohnnnn(ctx: Context) {
    await ctx.render("test3");
  }
  async gonbh(ctx: Context) {
    await ctx.render("nbh");
  }
  async gornbh(ctx: Context) {
    await ctx.render("rnbh");
  }
  async fabudailyrecord(ctx: Context) {
    const arrimgs = ctx.request.body?.imgs;
    const content = ctx.request.body?.content;
    if (!arrimgs && !content) {
      return resp.error(ctx, "上传图片和内容不能都为空");
    }
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token非法");
    }
    let dealRes = await dailyModel.create({
      imgs: arrimgs,
      content: content,
      userid: vres.data.id,
    });
    if (dealRes) {
      resp.success(ctx, dealRes);
    }
  }
  async getfabudailyrecord(ctx: Context) {
    const userfabuinfo = await dailyModel.aggregate([
      {
        $lookup: {
          from: "userinfos", // 关联 userinfo 表
          localField: "userid", // 根据 dailyModel 里 userid 字段查询
          foreignField: "_id", // 查找 userinfos 表里对应的 _id 的数据
          as: "info", // 返回的字段别名
        },
      },
      // // 创建一个 mongoDB 的 ObjectId: mongoose.Types.ObjectId
      // {
      //   $match: {
      //     userid: new mongoose.Types.ObjectId("638f0e1ff8f9c1ba9d6abaab"),
      //   },
      // }, //过滤条件
      {
        $project: {
          __v: 0,

          info: {
            __v: 0,
            password: 0,
          },
        },
      }, //过滤输出条件
    ]);
    let s;
    let flag: any = ctx.query.flag;
    let pageSize: any = ctx.query.pagesize || 10;
    let pageNumber: any = ctx.query.pagenumber || 1;

    if (flag == "true") {
      s = pageFilter(JSON.parse(JSON.stringify(userfabuinfo.reverse())), pageSize, pageNumber);
      if (s.list) {
        for (let e of s.list) {
          e.createTime = fromTime(e.createTime);
          let res = await plModel.find({ beplarticleid: e._id });
          let ss = JSON.parse(JSON.stringify(res));
          for (let ea of ss) {
            ea.createTime = fromTime(ea.createTime);
            let ress = await userModel.find({ _id: ea.plid });
            ea.userInfo = ress;
          }
          e.plInfo = ss.reverse();
          e.plNum = e.plInfo.length;
        }
        resp.success(ctx, s);
      }
    } else {
      s = JSON.parse(
        JSON.stringify(userfabuinfo.filter((e) => e.status == true))
      );
      if (s) {
        for (let e of s) {
          e.createTime = fromTime(e.createTime);
          let res = await plModel.find({ beplarticleid: e._id });
          let ss = JSON.parse(JSON.stringify(res));
          for (let ea of ss) {
            ea.createTime = fromTime(ea.createTime);
            let ress = await userModel.find({ _id: ea.plid });
            ea.userInfo = ress;
          }
          e.plInfo = ss.reverse();
          e.plNum = e.plInfo.length;
        }

        resp.success(ctx, s.reverse());
      }
    }


  }
  async adddianzan(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被点赞者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let dianzanRes = await dianzanModel.create({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (dianzanRes) {
      resp.success(ctx, dianzanRes, "添加点赞成功");
    }
  }
  async addshoucang(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被收藏者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let shoucangRes = await shoucangModel.create({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (shoucangRes) {
      resp.success(ctx, shoucangRes, "添加收藏成功");
    }
  }

  async addfocus(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被关注者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let focusRes = await focusModel.create({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (focusRes) {
      resp.success(ctx, focusRes, "添加关注成功");
    }
  }
  async addhistory(ctx: Context) {
    const rules: Rules = {
      behistoryid: [
        {
          type: "string",
          required: true,
          message: "查看的新闻id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      behistoryid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }

    let historyRes = await historyModel.create({
      userid: vres.data.id,
      behistoryid: data.behistoryid,
    });
    if (historyRes) {
      resp.success(ctx, historyRes, "添加新闻记录成功");
    }
  }
  async cancelfocus(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被关注者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let focusRes = await focusModel.deleteOne({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (focusRes) {
      if (focusRes.deletedCount == 0) {
        return resp.success(ctx, [], "无此取消关注对象");
      }
      resp.success(ctx, focusRes, "取消关注成功");
    }
  }
  async canceldianzan(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被关注者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let focusRes = await dianzanModel.deleteOne({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (focusRes) {
      if (focusRes.deletedCount == 0) {
        return resp.success(ctx, [], "无此取消点赞对象");
      }
      resp.success(ctx, focusRes, "取消点赞成功");
    }
  }
  async cancelshoucang(ctx: Context) {
    const rules: Rules = {
      befocusid: [
        {
          type: "string",
          required: true,
          message: "被关注者id不能为空",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      befocusid: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    let focusRes = await shoucangModel.deleteOne({
      userid: vres.data.id,
      befocusid: data.befocusid,
    });
    if (focusRes) {
      if (focusRes.deletedCount == 0) {
        return resp.success(ctx, [], "无此取消收藏对象");
      }
      resp.success(ctx, focusRes, "取消收藏成功");
    }
  }
  async getfocuslist(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }

    let focusRes = await focusModel.find({
      userid: new mongoose.Types.ObjectId(vres.data.id),
    });
    let s = JSON.parse(JSON.stringify(focusRes));
    for (let e of s) {
      let bedianzannumber = await userModel.find(
        { _id: e.befocusid },
        { password: 0, __v: 0 }
      );
      e.userInfo = bedianzannumber;
      e.createTime = dealTime(e.createTime);
    }
    if (focusRes) {
      resp.success(ctx, s, "获取关注列表成功");
    }
  }
  async gethistorylist(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }

    let historyRes = await historyModel.find({
      userid: new mongoose.Types.ObjectId(vres.data.id),
    });
    let s = JSON.parse(JSON.stringify(historyRes));
    for (let e of s) {
      let bedianzannumber = await newsInfo.find(
        { _id: e.behistoryid },
        { __v: 0 }
      );
      e.historyInfo = bedianzannumber;
      e.createTime = fromTime(e.createTime);
    }
    if (historyRes) {
      resp.success(ctx, s, "获取历史记录成功");
    }
  }
  async getdianzanlist(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }

    let focusRes: any = await dianzanModel.find({
      userid: new mongoose.Types.ObjectId(vres.data.id),
    });
    let s = JSON.parse(JSON.stringify(focusRes));
    for (let e of s) {
      let bedianzannumber = await dianzanModel.find({ befocusid: e.befocusid });
      e.befoverInfo = bedianzannumber;
    }
    // //去重
    // let obj: any = {};
    // let res = focusRes.reduce(function (preValue: any, item: any) {
    //   obj[item.key] ? "" : (obj[item.key] = true && preValue.push(item));
    //   console.log(obj, "obj2");
    //   return preValue;
    // }, []); //将返回值的初始值定义为空数组

    // console.log(res);
    //去重
    if (focusRes) {
      resp.success(ctx, s, "获取点赞列表成功");
    }
  }
  async getshoucanglist(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    let a: any = await shoucangModel.find({ userid: vres.data.id });
    let s = JSON.parse(JSON.stringify(a));
    for (let e of s) {
      //2 便利文章被点赞的文章
      let b = await dailyModel.find({ _id: e.befocusid });
      let ss = JSON.parse(JSON.stringify(b));

      for (let ea of ss) {
        ea.createTime = fromTime(ea.createTime);
        let sss = await userModel.find({ _id: ea.userid });
        e.userInfo = sss;
      }
      //去出自己
      // b = b.filter((i) => i.userid != vres.data.id);
      e.articleInfo = ss;
    }
    resp.success(ctx, s, "获取收藏列表成功");
  }
  async getsddzInfo(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    //1 找到登录用户所有的文章
    let a: any = await dailyModel.find({ userid: vres.data.id });
    let s = JSON.parse(JSON.stringify(a));
    for (let e of s) {
      //2 便利文章被点赞的文章
      let b = await dianzanModel.find({ befocusid: e._id });
      let ss = JSON.parse(JSON.stringify(b));
      for (let ea of ss) {
        ea.createTime = fromTime(ea.createTime);
      }
      //去出自己
      // b = b.filter((i) => i.userid != vres.data.id);
      e.articleInfo = ss;
    }

    for (let e of s) {
      let aaa = [];
      for (let e1 of e.articleInfo) {
        let c = await userModel.find({ _id: e1.userid });
        aaa.push(JSON.parse(JSON.stringify(c)));
        e.userInfo = aaa.flat();
      }
    }
    resp.success(ctx, s);
  }
  async addpl(ctx: Context) {
    const rules: Rules = {
      beplarticleid: [
        {
          type: "string",
          required: true,
          message: "被评论文章id不能为空",
        },
      ],
      beplid: [
        {
          type: "string",
          required: true,
          message: "被评论id不能为空",
        },
      ],
      plcontent: [
        {
          type: "string",
          required: true,
          message: "评论内容不能为空",
        },
      ],
      isParent: [
        {
          type: "boolean",
        },
      ],
      beplplid: [
        {
          type: "string",
        },
      ],
    };
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    type INFO = {
      beplarticleid: string;
      beplid: string;
      plcontent: string;
      isParent?: boolean;
      beplplid?: string;
    };
    const { data, error } = await validate<INFO>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }

    let plRes = await plModel.create({
      plid: vres.data.id,
      beplarticleid: data.beplarticleid,
      beplid: data.beplid,
      plcontent: data.plcontent,
      isParent: data?.isParent,
      beplplid: data?.beplplid || null,
    });
    if (plRes) {
      resp.success(ctx, plRes, "添加评论记录成功");
    }
  }
  async getplInfo(ctx: Context) {
    let token = ctx.request.header.authorization?.split(" ")[1];
    if (!token) {
      return resp.error(ctx, "token为空", 401);
    }
    let vres: any = verify(token);
    if (vres.code != 200) {
      return resp.error(ctx, "token错误或失效", 401);
    }
    let res = await plModel.find({ beplid: vres.data.id });
    let s = JSON.parse(JSON.stringify(res));
    for (let e of s) {
      let ress = await userModel.find({ _id: e.plid });
      e.userinfo = ress;
    }
    for (let e of s) {
      let resss = await userModel.find({ _id: e.beplid });
      e.userinfoa = resss;
    }
    resp.success(ctx, s);
  }
  async getAllNewsList(ctx: Context) {
    const pageSize = ctx.request.body.pageSize;
    const pageNumber = ctx.request.body.pageNumber;
    let filterRes = await newpageFilter(newsInfo, pageNumber, pageSize);
    resp.success(ctx, filterRes);
  }
}
const getUserInfo = new userInfo();
export { getUserInfo };
